package leetcode.tree;

/**
 * @author wangmaolin1
 * @date 2021/12/29 下午11:02
 */
public class _404左叶子之和 {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        TreeNode node = root;
        int sum = 0;
        TreeNode pre = root;
        sum += doSum(node, pre);
        return sum;
    }

    /**
     * 前序遍历
     * 判断是否为左叶子：左右节点为空，且pre 节点的左节点为当前节点
     */
    private int doSum(TreeNode node, TreeNode pre) {
        int sum = 0;
        if (node == null) {
            return 0;
        }
        if (isLeftLeaves(node, pre)) {
           return node.val;
        }
        if (node.left != null) {
            sum += doSum(node.left, node);
        }
        if (node.right != null) {
            sum += doSum(node.right, node);
        }
        return sum;

    }

    private boolean isLeftLeaves(TreeNode temp, TreeNode pre) {
        return temp.left == null && temp.right == null && pre.left != null && pre.left.equals(temp);
    }

    /**
     * 3 9   20 15   7
     *
     * @param args
     */
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(new _404左叶子之和().sumOfLeftLeaves(root));
    }
}
